package com.szh.zx.javacorecorret.chap2.two;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

// 章节 2.2.3
// 借助 CyclicBarrier 类具有计数重置性实现多赛段的比赛实验
public class CyclicBarrierTest3 {
	public static void main(String[] args) {
		CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
		MyService3 service = new MyService3(cyclicBarrier);

		Thread3 th1 = new Thread3(service);
		th1.setName("A");
		th1.start();

		Thread3 th2 = new Thread3(service);
		th1.setName("2");
		th2.start();

		Thread3 th3 = new Thread3(service);
		th1.setName("3");
		th3.start();

		Thread3 th4 = new Thread3(service);
		th1.setName("4");
		th4.start();
	}
}
class MyService3 {
	private CyclicBarrier cbRef;

	public void beginRun(){
		try {
			long sleepValue = (int) (Math.random() * 10 * 1000);
			Thread.sleep(sleepValue);
			System.out.println(Thread.currentThread().getName()+" "+System.currentTimeMillis()+" begin跑第一阶段"+(cbRef.getNumberWaiting()+1));

			cbRef.await();

			System.out.println(Thread.currentThread().getName()+" "+System.currentTimeMillis()+" end跑第一阶段"+(cbRef.getNumberWaiting()));
			// 第二阶段
			sleepValue= (int) (Math.random() * 10 * 1000);
			Thread.sleep(sleepValue);
			System.out.println(Thread.currentThread().getName()+" "+System.currentTimeMillis()+" begin跑第二阶段"+(cbRef.getNumberWaiting()+1));

			cbRef.await();

			System.out.println(Thread.currentThread().getName()+" "+System.currentTimeMillis()+" end跑第二阶段"+(cbRef.getNumberWaiting()));
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
	}

	public MyService3(CyclicBarrier cbRef) {
		this.cbRef = cbRef;
	}
}

class Thread3 extends Thread{

	private MyService3 service;

	public Thread3(MyService3 service) {
		this.service = service;
	}

	@Override
	public void run() {
		service.beginRun();
	}
}